/**
 * author:Administrator
 * date:2016/1/6
 * desc:TODO
 */

'use strict';

var Model = require('../model/account.js');
var Sequelize = require('sequelize');
var sequelize = require('../conn/sequelize.js');

var dao = {};
module.exports = dao;

/**
 * create
 * @param name
 * @param mony
 * @returns {*}
 */
dao.create = function*(name, money) {
  var account = yield Model.create({
    name: name,
    money: money
  });
  return account;
};

/**
 * update
 * @param id
 * @param kvs kvpairs for update
 */
dao.update = function*(id, kvs) {
  return yield Model.update(kvs, {where: {id: id}});
};

/**
 * query
 */
dao.findById = function *(id) {
  return yield Model.findOne({where: {id: id}});
};

/**
 * delete
 * @param id
 * @returns {*}
 */
dao.deleteById = function*(id) {
  return yield Model.destroy({where: {id: id}, force: true});
};

dao.transaction = function (from, to, money) {

  function tchain(t) {
    // update from account, balance -= money
    return Model.update(
      {money: sequelize.literal('money-' + money)},
      {
        where: {id: from, money: {gte: money}},
        transaction: t
      }
    )

      .then(function (result) {
        if (result == 0) { // edit count = 0
          console.log('from account not exist or insufficient money');
          throw new Error('from account not exist or insufficient money');
        }
        // update to account, balance += money
        return Model.update(
          {money: sequelize.literal('money+' + money)},
          {
            where: {id: to},
            transaction: t
          }
        );
      })

      .then(function (result) {
        if (result == 0) { // edit count = 0
          console.log('to account not exist');
          throw new Error('to account not exist');
        }
        return result;
      });
  }

  return sequelize.transaction({
    autocommit: false
  }).then(function (t) {
    return tchain(t)
      .then(function (result) {
        t.commit();
        console.log('transaction commited');
        return {errcode: 0};
      }).catch(function (err) {
        t.rollback();
        console.log('transaction rolled back,err=', err);
        return {errcode: 1, errmsg: err.toString()};
      });
  });
};
